#!/bin/env python
import pickle
import matplotlib.pyplot as plt
import numpy as np

#----------
# Parameters
#----------
tfkinds = {1:'TC+QSF',2:'TC',3:'QSF',4:'Others'}

file_obs = "./Data/data_tfdays_observations.pickle"
file_hiflor = "./Data/data_tfdays_HiFLOR.pickle"
file_spear = "./Data/data_tfdays_SPEAR.pickle"

colors1 = ['lightpink','yellow','cyan','lightgray','lightcoral','orange','magenta','slateblue']
colors2 = ['lightpink','cyan','lightgray','lightcoral','orange','magenta','slateblue']

#----------
# Subroutine
#----------
def tfdays_stat(tfdays):
    unique, tfdays_count =  np.unique(tfdays, return_counts=True)
    unique2 = [tfkinds[uu] for uu in unique]
  
    return unique2, tfdays_count

class MacOSFile(object):

    def __init__(self, f):
        self.f = f

    def __getattr__(self, item):
        return getattr(self.f, item)

    def read(self, n):
        # print("reading total_bytes=%s" % n, flush=True)
        if n >= (1 << 31):
            buffer = bytearray(n)
            idx = 0
            while idx < n:
                batch_size = min(n - idx, 1 << 31 - 1)
                # print("reading bytes [%s,%s)..." % (idx, idx + batch_size), end="", flush=True)
                buffer[idx:idx + batch_size] = self.f.read(batch_size)
                # print("done.", flush=True)
                idx += batch_size
            return buffer
        return self.f.read(n)

    def write(self, buffer):
        n = len(buffer)
        print("writing total_bytes=%s..." % n, flush=True)
        idx = 0
        while idx < n:
            batch_size = min(n - idx, 1 << 31 - 1)
            print("writing bytes [%s, %s)... " % (idx, idx + batch_size), end="", flush=True)
            self.f.write(buffer[idx:idx + batch_size])
            print("done.", flush=True)
            idx += batch_size

def pickle_load(file_path):
    with open(file_path, "rb") as f:
        return pickle.load(MacOSFile(f))

#----------
# Main
#----------
tfdays_obs = pickle_load(file_obs)
tfdays_hiflor = pickle_load(file_hiflor)
tfdays_spear = pickle_load(file_spear)


fig = plt.figure(figsize=(8,16)) # set figure environemnt

# observations
ax1 = plt.subplot(3,1,1)

unique2, tfdays_count = tfdays_stat(tfdays_obs)

paches, texts, junks = plt.pie(tfdays_count,labels=unique2, colors=colors2, counterclock=False, startangle=90, autopct="%1.1f%%")
plt.title("(b) Observatoins", fontsize=26)

for t in texts[:]:
   #t.set_horizontalalignment('center')
    t.set_size(24)
    
for t in junks[:]:
   #t.set_horizontalalignment('center')
    t.set_size(24)

# HiFLOR
ax1 = plt.subplot(3,1,2)
unique2, tfdays_count = tfdays_stat(tfdays_hiflor)

paches, texts, junks = plt.pie(tfdays_count,labels=unique2, colors=colors1, counterclock=False, startangle=90, autopct="%1.1f%%")
plt.title("(c) HiFLOR", fontsize=26)

for t in texts[:]:
   #t.set_horizontalalignment('center')
    t.set_size(24)
    
for t in junks[:]:
   #t.set_horizontalalignment('center')
    t.set_size(24)

# HiFLOR
ax1 = plt.subplot(3,1,3)
unique2, tfdays_count = tfdays_stat(tfdays_spear)

paches, texts, junks = plt.pie(tfdays_count,labels=unique2, colors=colors1, counterclock=False, startangle=90, autopct="%1.1f%%")
plt.title("(d) SPEAR", fontsize=26)

for t in texts[:]:
   #t.set_horizontalalignment('center')
    t.set_size(24)
    
for t in junks[:]:
   #t.set_horizontalalignment('center')
    t.set_size(24)
    
    
fig.tight_layout()
#plt.show()

fig.savefig("./Fig3b.png")
